package com.learn.smart.framework.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.learn.smart.framework.ConfigConstant;
import com.learn.smart.framework.helper.ConfigHelper;
import com.learn.smart.framework.util.PropsUtil;

public class MyBatis {
	
	private static final Logger log = LoggerFactory.getLogger(MyBatis.class);
	
	private static SqlSessionFactory SQL_SESSION_FACTORY;
	
	private static ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<SqlSession>();
	
	static{
		Properties properties = ConfigHelper.getProperties();
		String resource = PropsUtil.getString(properties, ConfigConstant.MYBATIS_CONFIG);
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream(resource);
		} catch (IOException e) {
			log.error("读取资源文件失败 ",e);
			e.printStackTrace();
		}
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		SQL_SESSION_FACTORY = sqlSessionFactoryBuilder.build(inputStream,properties);
		Configuration  configuration  =SQL_SESSION_FACTORY.getConfiguration();
		configuration.addMappers(PropsUtil.getString(properties, ConfigConstant.MYBATIS_PACKAGES));
	}
	
	//获取SqlSession
	public static void getSqlSession(){
		SqlSession sqlSession = THREAD_LOCAL.get();
		if(sqlSession==null){
			sqlSession = createDefaultSqlSession();
			THREAD_LOCAL.set(sqlSession);
		}
	}
	
	public static void beginTransaction(){
		
	}
	
	//创建默认SqlSession
	private static SqlSession createDefaultSqlSession(){
		return createSqlSession(true);
	}
	
	private static SqlSession createSqlSession(boolean bool){
		return SQL_SESSION_FACTORY.openSession(bool);
	}

}
